package com.by_man.presenter.module_health_records.upload_health_records;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.module_gestureLock.GestureLockActivity;
import com.by_man.presenter.module_health_records.image.AllImages;
import com.by_man.presenter.module_health_records.image.BitmapManager;
import com.by_man.presenter.module_health_records.image.BucketImgList;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * Created by man on 2017-03-05.
 */
public class AllPhotoOfAlbumActivity extends AppCompatActivity {
    private BucketImgList imgs;
    private ViewHloder views;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_photo_album);
        AllImages allImages = AllImages.getInstance();
        int index = getIntent().getIntExtra("position", 0);
        ArrayList<BucketImgList> buckets = allImages.getAllImgs(false);
        imgs = buckets.get(index);
        initView();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(this, AlbumActivity.class);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void onRestart()
    {
        super.onRestart();
        Intent intent=new Intent(this,GestureLockActivity.class);
        intent.putExtra("class",this.getClass().getName());
        intent.putExtra("position", 0);
        startActivity(intent);
    }

    private void initView() {
        views = new ViewHloder();
        views.album = (Button) findViewById(R.id.showallphoto_back);
        views.cancel = (Button)findViewById(R.id.showallphoto_cancel);
        views.title = (TextView)findViewById(R.id.showallphoto_headtitle);
        views.preview = (Button) findViewById(R.id.showallphoto_preview);
        views.ok = (Button) findViewById(R.id.showallphoto_ok_button);
        views.gridView = (GridView)findViewById(R.id.showallphoto_myGrid);

        views.title.setText(imgs.bucketName);
        views.cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BitmapManager.images.clear();
                Intent intent = new Intent(AllPhotoOfAlbumActivity.this, UploadHealthRecordsActivity.class);
                startActivity(intent);
            }
        });
        views.album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AllPhotoOfAlbumActivity.this, AlbumActivity.class);
                startActivity(intent);
            }
        });
        views.ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AllPhotoOfAlbumActivity.this, UploadHealthRecordsActivity.class);
                startActivity(intent);
            }
        });
        views.preview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AllPhotoOfAlbumActivity.this, PhotoGalleryActivity.class);
                startActivity(intent);
            }
        });

        views.gridView.setAdapter(new GridViewAdapter());

    }

    // 封装页面的所有组件
    private class ViewHloder{
        Button album;
        TextView title;
        Button cancel;
        Button preview;
        Button ok;
        GridView gridView;
    }

    private class GridViewAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return imgs.imgList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position,View convertView,ViewGroup parent) {
            ViewHolder viewHolder;
            if (null == convertView) {
                convertView = getLayoutInflater().inflate(R.layout.item_grid_view_chose_photo, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.imageView = (ImageView) convertView.findViewById(R.id.image_view);
                viewHolder.toggleButton = (ToggleButton) convertView.findViewById(R.id.toggle_button);
                viewHolder.choosetoggle = (Button) convertView.findViewById(R.id.choosedbt);
                convertView.setTag(viewHolder);
            }
            viewHolder = (ViewHolder)convertView.getTag();
            setButton();
            viewHolder.toggleButton.setTag(viewHolder.choosetoggle);
            viewHolder.choosetoggle.setTag(position);
            viewHolder.toggleButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToggleButton button = (ToggleButton) view;
                    Button choose = (Button) button.getTag();
                    int p = (Integer) choose.getTag();
                    if (BitmapManager.images.size() >= BitmapManager.max) {
                        button.setChecked(false);
                        choose.setVisibility(View.GONE);
                        getWarn();
                    }
                    // 这块逻辑有点难
                    if (button.isChecked()) {
                        choose.setVisibility(View.VISIBLE);
                        BitmapManager.images.add(imgs.imgList.get(p));
                        //ok.setText("ok" + "(" + selectedImgs.size() + "/"
                        //  + BitmapManager.max + ")");
                    } else {
                        BitmapManager.images.remove(imgs.imgList.get(p));
                        choose.setVisibility(View.GONE);
                        //ok.setText("ok" + "(" + selectedImgs.size() + "/"
                        //        + BitmapManager.max + ")");
                    }
                    setButton();
                }
            });
            loadImage(position, viewHolder.imageView);
            return convertView;
        }

        // 动态按钮设定
        private void setButton() {
            if (BitmapManager.images.size() > 0) {
                views.preview.setPressed(true);
                views.ok.setPressed(true);
                views.preview.setClickable(true);
                views.ok.setClickable(true);
                views.preview.setTextColor(Color.WHITE);
                views.ok.setTextColor(Color.WHITE);
                views.ok.setText("ok" + "(" + BitmapManager.images.size() + "/"
                        + BitmapManager.max + ")");
            } else {
                views.preview.setPressed(false);
                views.ok.setPressed(false);
                views.preview.setClickable(false);
                views.ok.setClickable(false);
                views.preview.setTextColor(Color.parseColor("#E1E0DE"));
                views.ok.setTextColor(Color.parseColor("#E1E0DE"));
                views.ok.setText("ok" + "(" + BitmapManager.images.size() + "/"
                        + BitmapManager.max + ")");
            }
        }

        // 给出警告信息
        private void getWarn(){
            SharedApplication.showToast(AllPhotoOfAlbumActivity.this, "只能选择"+BitmapManager.max+"张图片！");
        }

        private class ViewHolder {
            public ImageView imageView;
            public ToggleButton toggleButton;
            public Button choosetoggle;
            public TextView textView;
        }

        /***********************************************************
         * 异步加载
         ***********************************************************/
        private class AsyncImageLoader extends AsyncTask<Integer, Void, Bitmap> {
            public int position;
            private final WeakReference<ImageView> imageViewWeakReference;

            public AsyncImageLoader(ImageView imageView){
                imageViewWeakReference = new WeakReference<ImageView>(imageView);
            }

            @Override
            protected Bitmap doInBackground(Integer...params) {
                position = params[0];
                String imgPath = imgs.imgList.get(position).imagePath;
                String thumbnailPath = imgs.imgList.get(position).thumbnailPath;
                Bitmap bitmap;
                if (null == thumbnailPath) {
                    bitmap = BitmapManager.getCompressBitmap(imgPath, 200,200);
                } else {
                    bitmap = BitmapManager.getCompressBitmap(thumbnailPath,200,200);
                    if (null == bitmap) {
                        bitmap = BitmapManager.getCompressBitmap(imgPath,200,200);
                    }
                }
                BitmapManager.putBitmap(imgPath,bitmap);
                return bitmap;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap){
                if (imageViewWeakReference != null && bitmap != null) {
                    ImageView imageView = imageViewWeakReference.get();
                    imageView.setImageBitmap(bitmap);
                }
            }
        }

        public AsyncImageLoader getAsyncImageLoader(ImageView imageView) {
            WeakReference<AsyncImageLoader> info = (WeakReference<AsyncImageLoader>) imageView.getTag();
            if (info != null) {
                return info.get();
            }
            return null;
        }

        public boolean cancelAsyncWork(int position, ImageView imageView) {
            AsyncImageLoader imageLoader = getAsyncImageLoader(imageView);
            if (null != imageLoader) {
                if (imageLoader.position != position) {
                    imageLoader.cancel(true);
                } else {
                    return false;
                }
            }

            return true;
        }

        public void loadImage(int position,ImageView imageView) {
            String imgPath = imgs.imgList.get(position).imagePath;
            Bitmap bitmap = BitmapManager.getBitmap(imgPath);
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            } else {
                if (cancelAsyncWork(position, imageView)) {
                    AsyncImageLoader imageLoader = new AsyncImageLoader(imageView);
                    WeakReference<AsyncImageLoader> loaderWeakReference = new WeakReference<AsyncImageLoader>(imageLoader);
                    imageView.setTag(loaderWeakReference);
                    imageLoader.execute(position);
                }
            }
        }

    }

}
